package  net.siufung.market.base.user.provider;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.base.Strings;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.siufung.core.model.enums.DeletedEnum;
import net.siufung.core.model.enums.InitializeEnum;
import net.siufung.core.utils.StringPool;
import net.siufung.market.base.tenant.api.ITenantUserApi;
import net.siufung.market.base.tenant.api.dto.TenantUserCreateDto;
import net.siufung.market.base.tenant.api.dto.TenantUserUpdateDto;
import net.siufung.market.base.user.enums.UserSupers;
import net.siufung.market.base.user.mapper.IUserMapper;
import net.siufung.market.base.user.mapper.entity.User;
import net.siufung.market.base.user.service.IUserService;
import net.siufung.security.api.service.passwd.ILoginPasswdService;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * @author 陈建峰
 * @since 2022/7/6 5:19 下午
 */
@Slf4j
@AllArgsConstructor
public class TenantUserProvider implements ITenantUserApi {

    private final IUserService userService;
    private final IUserMapper userMapper;
    private final ILoginPasswdService loginPasswdService;

    @Override
    public Boolean existUserByTenantPhone(String phone) {
        if(userMapper
                .selectCount(new LambdaQueryWrapper<User>().eq(User::getMobile, phone)) > 0){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TenantUserCreateDto createUserByTenant(TenantUserCreateDto tenantUserCreateDto) {
        User user = new User();
        String loginName = this.getRandomLoginName(8);
        user.setLoginName(loginName);
        user.setLoginPwd(loginPasswdService.getInitPassword());
        user.setInitFlag(InitializeEnum.NOT.getValue());
        user.setAdminState(UserSupers.IS.getValue());
        user.setTenantId(
                String.valueOf(tenantUserCreateDto.getTenantId()));
        user.setUserCode(getRandomUserCode(8));
        user.setMobile(tenantUserCreateDto.getPhone());
        if(Strings.isNullOrEmpty(tenantUserCreateDto.getPhone())){
            user.setMobile(StringPool.TEMP_MOBILE);
        } else {
            user.setUserName(tenantUserCreateDto.getContacts());
        }
        user.setUserName(loginName);
        if(!Strings.isNullOrEmpty(tenantUserCreateDto.getContacts())){
            user.setUserName(tenantUserCreateDto.getContacts());
        };
        userService.save(user);

        tenantUserCreateDto.setLoginName(loginName);
        tenantUserCreateDto.setUserId(user.getId());
        return tenantUserCreateDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserByTenant(TenantUserUpdateDto tenantUserUpdateDto) {
        userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId, tenantUserUpdateDto.getUserId())
                .set(!Strings.isNullOrEmpty(tenantUserUpdateDto.getPhone()),
                        User::getMobile, tenantUserUpdateDto.getPhone())
                .set(!Strings.isNullOrEmpty(tenantUserUpdateDto.getPhone()),
                        User::getUserName, tenantUserUpdateDto.getContacts()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserStatusById(Serializable tenantId, DeletedEnum deletedEnum) {
        userService.update(
                new LambdaUpdateWrapper<User>()
                        .eq(User::getTenantId, tenantId)
                        .set(User::getDeleted, deletedEnum.getValue()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeUserListById(Serializable tenantId) {
        userService.remove(
                new LambdaUpdateWrapper<User>().eq(User::getTenantId, tenantId));
    }

    /**
     * 获取登录名
     * @param length 随机码长度
     * @return String
     */
    private String getRandomLoginName(int length){
        String menuCode = RandomUtil.randomString(length);
        if(userMapper.selectCount(
                new LambdaQueryWrapper<User>().eq(User::getLoginName, menuCode)) > 0){
            menuCode = getRandomLoginName(length);
        }
        return menuCode;
    }

    /**
     * 获取用户编码
     * @param length 随机码长度
     * @return String
     */
    private String getRandomUserCode(int length){
        String menuCode = RandomUtil.randomString(length);
        if(userMapper.selectCount(
                new LambdaQueryWrapper<User>().eq(User::getUserCode, menuCode)) > 0){
            menuCode = getRandomUserCode(length);
        }
        return menuCode;
    }
}
